package com.itheima.filter;

import com.itheima.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
* 登录安全认证过滤器
*   未登录系统，不得访问工程的资源
* */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //session是否有登录者信息
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;

        //设置一些登录前必须要放行操作：login.jsp,/UserServlet/login,index.jsp
        String uri = req.getRequestURI();
        if("/studentInfo/pages/index.jsp".equals(uri)||"/studentInfo/css/allCss.css".equals(uri)||"/studentInfo/pages/login.jsp".equals(uri)||"/studentInfo/UserServlet/login".equals(uri)){
            filterChain.doFilter(req,resp);
        }else {
            //获取session对象
            HttpSession session = req.getSession();
            //从session中获取登陆者信息
            User user = (User) session.getAttribute("user");
            if(user!=null){//已登录
                filterChain.doFilter(req,resp);
            }else {//未登录，回登录页面
                resp.sendRedirect(req.getContextPath()+"/pages/index.jsp");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
